package com.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pojo.QuestionBase;
import com.pojo.Rewind;
import com.service.QuestionService;
import com.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@CrossOrigin("*")
@RequestMapping("/question")
public class QuestionAction {
    @Autowired
    private QuestionService questionService;

    @RequestMapping("/addOrUpdateQuestion")
    public ResponseBean addOrUpdateQuestion(@RequestParam Map map){
        QuestionBase questionBase = JSONObject.parseObject(JSON.toJSONString(map),QuestionBase.class);
        return new ResponseBean(0,0,questionService.saveOrUpdate(questionBase));
    }

    @RequestMapping("/searchQuestion")
    public ResponseBean searchQuestion(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int limit, @RequestParam Map m){
        IPage iPage = questionService.searchQuestion(page,limit,m);
        return new ResponseBean(0,iPage.getTotal(),iPage.getRecords());
    }
    @RequestMapping("/subjects")
    public ResponseBean subjects(){
        return new ResponseBean(200,0,JSON.toJSONString(questionService.subjects()));
    }

    @RequestMapping("/chapters")
    public ResponseBean chapters(){
        return new ResponseBean(200,0,JSON.toJSONString(questionService.chapters()));
    }

    /**
     *  随机查询试题库中的试题
     * @param username 用户账号
     * @param num 每个类型的试题数量( , 隔开)
     * @return
     */
    @RequestMapping("/examinationQuestion")
    public ResponseBean examinationQuestion(String username,String num,Integer chapter){

        //随机查询试题库中的试题
        Map map=questionService.examinationQuestion(username,num,chapter);
        if(map!=null){
            return new ResponseBean(200,0,map);
        }
        return new ResponseBean(500,0,null);
    }


    /**
     *  根据试卷id查询试卷中的题目
     * @param username  用户账号  用于缓存的key
     * @param testId  试卷id
     * @return
     */
    @RequestMapping("/queryTest")
    public ResponseBean queryTest(String username , Integer testId){
        // 根据试卷id查询试卷中的题目
        Map map= questionService.queryTest(username,testId);
        if(map!=null){
            return new ResponseBean(200,0,map);
        }
        return new ResponseBean(500,0,null);
    }


    /**
     * 删除redis缓存中的数据
     * @param username  缓存数据的key
     * @return
     */
    @RequestMapping("/deleteData")
    public ResponseBean deleteTest(String username){
        // 判断缓存中数据是否删除
        boolean f=questionService.deleteTest(username);
        // true:删除成功    false:删除失败
        return new ResponseBean(0,0,f);
    }


}
